﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.UI;
using SingleUserMall.Common;
using SingleUserMall.Videos.Form;
using SingleUserMall.Videos.VO;

namespace SingleUserMall.Videos
{
    public class VideoManageAppService : SingleUserMallAppServiceBase, IVideoManageAppService
    {

        private readonly IRepository<Video, long> _videoRepository;
        public VideoManageAppService(IRepository<Video, long> videoRepository)
        {
            _videoRepository = videoRepository;
        }

        public async Task<PagedResultDto<VideoVO>> GetVideosAsync(VideoPagedForm form)
        {
            var query = _videoRepository.GetAll()
           .WhereIf(!string.IsNullOrEmpty(form.Keywords), x => x.Name.Contains(form.Keywords) && x.Content.Contains(form.Keywords))
          .OrderByDescending(x => x.CreationTime);
            return await query.ToPagedResultDtoAsync<Video, VideoVO>(form);
        }
        public async Task SaveVideoAsync(VideoForm form)
        {
            try
            {
                var video = await _videoRepository.FirstOrDefaultAsync(x => x.Id == form.Id);
                if (video != null)
                {
                    video = form.MapTo(video);
                    video.Name = form.Name;
                    video.Content = form.Content;
                    await _videoRepository.UpdateAsync(video);
                }
                else
                {
                    video = form.MapTo<Video>();
                    video.Name = form.Name;
                    video.Content = form.Content;
                    await _videoRepository.InsertAsync(video);

                }
                await CurrentUnitOfWork.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }
        public async Task RemoveVideoAsync(SingleId<long> form)
        {
            await _videoRepository.DeleteAsync(x => x.Id == form.Id);
        }
    }
}
